import axios from 'axios'
import { ElMessage } from 'element-plus'
import {storage} from '../utils/storage'
// 创建axios实例
const service=axios.create({
    baseURL:process.env.VITE_API_URL,
    timeout:30000,
    headers:{
        "Content-Type":"application/json;charset=UTF-8"
    }
})
// 请求拦截
service.interceptors.request.use((config)=>{
    config.headers=config.headers||{}
    if(storage.get('token')){
        config.headers.token=storage.get('token')||""
        console.log('请求拦截了');
    }
    return config
},error=>{
    Promise.reject(error)
})
// 响应拦截
service.interceptors.request.use(res=>{
    const code:number=res.data.code
    if(code!=200){
        return Promise.reject(res.data)
    }
    console.log('请求响应了');
    return res
},(err)=>{
    ElMessage({
        message: '服务器无响应',
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(err)
})

const http= {
    post(url:string,data:any){
        return new Promise((resolve, reject) => {
            service({
                    method: 'post',
                    url:url,
                    data:data,
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                });
        })
    },
    get(url:string,data:any){
        return new Promise((resolve, reject) => {
            service({
                    method: 'get',
                    url:url,
                    data:data,
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                });
        })
    },
    put(url:string,data:any){
        return new Promise((resolve, reject) => {
            service({
                    method: 'put',
                    url:url,
                    data:data,
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                });
        })
    },
    delete(url:string,data:any){
        return new Promise((resolve, reject) => {
            service({
                    method: 'delete',
                    url:url,
                    data:data,
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                });
        })
    }
};
export default http